package com.linkgie.galaxyframework.utils.bean;

import java.beans.PropertyEditorSupport;

import com.linkgie.galaxyframework.utils.StringConverter;

class BeanPropertyEditor extends PropertyEditorSupport {

	@SuppressWarnings("rawtypes")
	private StringConverter converter;

	private Class<?> valueType;

	BeanPropertyEditor(Class<?> valueType, StringConverter<?> converter) {
		this.valueType = valueType;
		this.converter = converter;
	}

	@Override
	public void setValue(Object value) {
		if (value == null) {
			super.setValue(value);
			return;
		}
		if (valueType.isAssignableFrom(value.getClass())) {
			super.setValue(value);
		}
		throw new IllegalArgumentException("Unsupported value type[" + value.getClass().getName() + "]!");
	}

	@Override
	public Object getValue() {
		return super.getValue();
	}

	@SuppressWarnings("unchecked")
	@Override
	public String getAsText() {
		Object value = getValue();
		if (value == null) {
			return null;
		}
		return converter.encode(value);
	}

	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		if (text == null) {
			super.setValue(null);
			return;
		}
		Object value = converter.decode(text);
		super.setValue(value);
	}

}